<?php
// +----------------------------------------------------------------------
// | 演出类产品预定
// +----------------------------------------------------------------------
// | Author: TongBC <50249101@qq.com>
// +----------------------------------------------------------------------
// | Date  : 2015/04/23
// +----------------------------------------------------------------------
class OrderSubmit_H extends OrderSubmit{
	protected $ph = null;
	public function __construct(SoapClient $s, ProductInfo $p, Member $m,$ordermode=0, $sale=1){
        parent::__construct($s,$p,$m,$ordermode,$sale);
    }
	
	public function order($option, $aid = 0, $debug = false)
    {
        $s = $this->s;
        $member = $this->m->memberID;
        $pid = $this->p->pid;

        $tnum        = $option['tnum'];
		$paymode     = $option['paymode'];
        $begintime   = $option['begintime'];
        $ordername   = $option['ordername'];
        $ordertel    = $option['ordertel'];
        $contacttel  = $option['contacttel'];
        $remoteorder = $option['remoteorder'];
        
        // 订单类型，normalOrder=>普通订单，linkOrder=>联票订单，packageOrder=>套票订单
        $orderType = 'normalOrder';
        $p_info = $this->p->pInfo();

        $endtime = ($p_info['delaydays'] - 1) < 0 ? 0 : ($p_info['delaydays'] - 1);
        $time = strtotime($begintime) + $endtime * 24 * 3600;
		
		$begintime = date("Y-m-d 00:00:00", strtotime($begintime));
        $endtime   = date("Y-m-d 23:59:59", $time);

        /*产品预订检查*/
        $totalMoney = 0;

        $account = $option['account'];
		
        // 新接口获取
        $tprice = $this->p->tPrice_n($this->sale, $begintime, $aid, '', $account);
        if(is_array($tprice)) throw new DisOrderException($tprice['msg']);
		
        $totalTprice = $tprice * $tnum;
        $totalMoney += $totalTprice;

        $pcode = 0;
        $ordermode = isset($option['ordermode']) ?$option['ordermode'] : $this->ordermode;

        if ($p_info['p_type'] == "B") { /*线路产品额外信息*/
            $playdateStr = explode("-", substr($begintime, 0, 10));
            $playdateStr = substr($playdateStr[0], 2, 2) . $playdateStr[1] . $playdateStr[2];
            $series = preg_replace('/{fck_date}/', $playdateStr, $p_info['series_model']); //团号
            $assembly = abs($_REQUEST['assembly']); //集合地点
        }
//        $proInfos=array();
        $c_infos = array();
        if ($p_info['p_type'] == "C") { //酒店按联票产品下单
            $leavetime = $option['leavetime'];
            $days = ceil((strtotime($leavetime) - strtotime($begintime)) / 24 / 3600);
            $orderType = $days > 1 ? 'linkOrder' : 'normalOrder';
            for ($n = 1; $n < $days; $n++) {
                try {
                    $date = date("Y-m-d", strtotime($begintime) + 3600 * 24 * $n);
                    $starttime = $date . " 00:00:00";
                    // $c_tprice=$cpro->tPrice($member,$begintime,$this->sale);
                    $c_tprice = $this->p->tPrice_n($this->sale, $starttime, $aid,
                        null, $account);
                    // 新接口
                    $c_tnum = $tnum;
                    $endtime = $date . " 23:59:59";
                    $c_infos[] = array("member" => $member,
                        "tprice" => $c_tprice, "tnum" => $c_tnum,
                        "ltitle" => $p_info['ltitle'],
                        "ttitle" => $p_info['ttitle'],
                        "pid" => $p_info['pid'],
                        "lid" => $p_info['lid'],
                        "tid" => $p_info['tid'],
                        "begintime" => $starttime,
                        "endtime" => $date . " 23:59:59",
                        "storage" => $p_info['storage'],
                        "storage_open" => $p_info['storage_open'],
                        "salerid" => $p_info['salerid'],
                        "ordername" => $ordername,
                        "ordertel" => $ordertel,
                        "paymode" => $paymode,
                        "ordermode" => $ordermode,
                        "apply_did" => $p_info['apply_did'],
                        "sapply_did" => $p_info['sapply_did'],
                        "contacttel" => $option['contacttel'],
                    );
                    $totalMoney += $c_tprice * $c_tnum;
                } catch (Exception $e) {
                }
            }
        } elseif ($p_info['p_type'] == "F") { //套票产品
            $pcode = 1;
            $orderType = 'packageOrder';
            //套票判定 Author:CGP
            $bt = substr($begintime, 0, 10);
            $chk_ret = \pft\Prod\Sale::PackageTicketCheck($s, $pid, $member, $aid,
                $bt, $tnum);
            if ($chk_ret['code'] !== 200) {
                $msg = $chk_ret['code'] > 908 ? "子票【{$chk_ret['pid']}】" : '';
                throw new DisOrderException($msg . $chk_ret['msg'] .  $member.'--'.$aid);
            }
        } else {
            /*查看是否存在联票产品，存在的话记录联票产品下单信息*/
            foreach ((array)$option['c_pids'] as $c_pid => $c_tnum) {
                if ($c_tnum > 0) {
                    $orderType = 'linkOrder';
                    $c_pid = abs($c_pid);
                    $c_about = $this->p->pInfo($c_pid);
                    // $c_tprice = $this->p->tPrice($member, $begintime, $this->sale, $c_pid);
                    $c_tprice = $this->p->tPrice_n($this->sale, $begintime, $aid,
                        $c_pid, $account);
                    // 新接口
                    $c_infos[$c_pid] = array(
                        "member" => $member,
                        "tprice" => $c_tprice,
                        "tnum" => $c_tnum,
                        "ltitle" => $c_about['ltitle'],
                        "ttitle" => $c_about['ttitle'],
                        "pid" => $c_pid,
                        "lid" => $c_about['lid'],
                        "tid" => $c_about['tid'],
                        "begintime" => $begintime,
                        "endtime" => $endtime,
                        "storage" => $c_about['storage'],
                        "storage_open" => $c_about['storage_open'],
                        "salerid" => $c_about['salerid'],
                        "ordername" => $ordername,
                        "ordertel" => $ordertel,
                        "paymode" => $paymode,
                        "ordermode" => $ordermode,
                        "apply_did" => $c_about['apply_did'],
                        "sapply_did" => $c_about['sapply_did'],
                        "contacttel" => $option['contacttel'],
                        "sfz" => $option['sfz'],
						"p_type"=>$p_info['p_type'],
						"round_id"=>$option['round_id'],
                    );
                    $totalMoney += $c_tprice * $c_tnum;
                }
            }
        }

        $smsSendAfterOrder = 0; //下单后发送短信0不发送1发送
        $smsSendWithOrder = 1; //下单并发送短信0发送1不发送
        $no_wx_notify = false;
        $isLnkOrder = count($c_infos); //是否联票订单
        $proInfos = $isLnkOrder ? $c_infos : array(); //联票购买
        $toProvider = 1;
		if($paymode==1){
			$toProvider = 0;
		}
        if ($paymode == 1 || $p_info['sendVoucher'] == 1) {
            //未支付或特殊设置不发送短信
            $no_wx_notify = true;
        } elseif ($isLnkOrder || $p_info['p_type'] == 'C') {
            //联票订单或酒店订单，下单后发送短信
            $smsSendAfterOrder = 1;
        } else {
            //跟随订单一起发送短信
            $smsSendWithOrder = 0;
        }


        $proInfos[] = array(
            "member" => $member,
            "tprice" => $tprice,
            "tnum" => $tnum,
            "ltitle" => $p_info['ltitle'],
            "ttitle" => $p_info['ttitle'],
            "pid" => $p_info['pid'],
            "tid" => $p_info['tid'],
            "begintime" => $begintime,
            "endtime" => $endtime,
            "storage" => $p_info['storage'],
            "storage_open" => $p_info['storage_open'],
            "sapply_did" => $p_info['sapply_did']
        );

        $this->orderCheck($option, $p_info); //预订判定
        //TODO::如果是零售（散客购买),就不判断购买权限，反正都是用零售价
        if (!$this->sale) {
            $this->authCheck($proInfos, $aid); //购买权限判定
        }

        // $this->storageCheck($proInfos); //库存判定
        $this->payCheck($totalMoney); //金额判定
		
		if($p_info['p_type'] == 'H'){// 生成座位表
			$seats_ids = array();
			$this->ph = new abc777\Product_H(\PFT\Db::connect());
			foreach($option['seat_data'] as $key_pid=>$row){
				$seats_tmp = $this->ph->dync_add_seat($option['round_id'], $option['venue_id'], $row['area_id'], $row['ticket_num']);
				if(count($seats_tmp)!=$row['ticket_num']) throw new DisOrderException('剩余座位不足');
				$seats_ids[$key_pid] = $seats_tmp;
				if(isset($c_infos[$key_pid])) $c_infos[$key_pid]['seats_ids'] = $seats_tmp;
			}
		}
		// print_r($seats_ids[$pid]);
		// exit;
        $r = $s->Group_Order_Submit($member, $p_info['lid'], $p_info['tid'],
            $begintime, $endtime, $tprice, $tnum, $totalTprice, $ordername,
            $ordertel, "$contacttel", $p_info['salerid'], $p_info['sapply_did'],
            $paymode, $ordermode, "$remoteorder", "$assembly", "$series",
            $smsSendWithOrder, 0, $pcode, $option['sfz']);

        $sendRut = '';
        if ($r >= 100000) {
			
			if($p_info['p_type'] == 'H'){// 更新座位信息
				if(!($resql=$this->ph->update_seat_order($r, $seats_ids[$pid]))){
					include '/var/www/html/new/d/class/abc/Syslog.class.php';
					abc777\Syslog::write($r.'-'.$seats_ids_str, 'show_product_update_order.txt');
				}
			}
			
			
            /*附属产品下单*/
            if ($isLnkOrder) {
                $this->subOrder($c_infos, $r);
            }
            //短信通知
            include '/var/www/html/new/d/class/OrderSmsManual.class.php';
            $smsManual = new \PFT\SMS\OrderSmsManual($s);
            $smsManual->SetParam($ordertel, $aid, $member, $p_info['tid'],
                $pid, $r, $p_info['lid']);
//            if ($_SESSION['account']==100019) {
//                var_dump( $smsManual->WxNotifyChk($member, 0, true));
//                echo $smsSendAfterOrder;
//                var_dump($smsSendWithOrder) ;
//                exit;
//            }
            //通知顾客-微信
            if(!$no_wx_notify) {
                if ($wx_open_id = $smsManual->WxNotifyChk($member, 0, true)) {
                    $itemData = '';
                    foreach($proInfos as $prod) {
                        $itemData .= "\n{$prod['ttitle']}:{$prod['tnum']} 张；";
                    }
                    $smsManual->WxNotifyCustomer(
                        $wx_open_id,
                        date('Y-m-d H:i:s'),
                        $ordername,
                        $p_info['ltitle'],
                        $itemData,
                        $r,
                        $totalTprice / 100
                    );
                }

            }
            if ($smsSendAfterOrder == 1) {
                $sms_ret = $smsManual->Send($p_info['ltitle'] . $p_info['ttitle'],
                    $tnum, $begintime, $endtime, $p_info['p_type']);
                if ($sms_ret != 100) {
                    self::log_result("短信发送失败|订单号[$r]|错误代码[{$sms_ret}]", '/var/www/html/new/d/logs/debug.txt');
//                    Log::writeLog("短信发送失败|订单号[$r]|错误代码[{$sms_ret}]", Log::ERROR_LOG_PATH);
                    $this->errHandle("短信发送失败[{$sms_ret}]", $r);
                }
            }
//            //通知供应商
            if ($toProvider==1) {
                if ($p_info['p_type'] == 'C') {
                    $smsManual->SmsToApplyErHotel($ordername,
                        $p_info['ltitle'] . $p_info['ttitle'],
                        $tnum, $begintime, $endtime, $r, $option['memo']);
                } else {
//                    self::log_result('发送供应商短信通知', '/var/www/html/new/d/logs/debug.txt');
                    $smsManual->OrderNotify('AFTER_SUBMIT', $proInfos, $ordername,
                        $r, $ordertel, $option['memo']);
                }
            }
            /*记录订单额外信息*/
            $this->appendInfo($r, $option);
            return array('orderNum' => $r, 'orderType' => $orderType, 'sendRut' => $sendRut);
        } else {
			
			if($p_info['p_type'] == 'H'){// 释放座位
				if(!$this->ph->release_dync_seat($option['round_id'])){
					include_once '/var/www/html/new/d/class/abc/Syslog.class.php';
					abc777\Syslog::write($_SESSION['sid'], 'show_product_seat_release.txt');
				}
			}
            $this->errHandle("下单接口出错", $r);
        }
    }
	
	public function subOrder($c_infos,$r,$remoteorder='',$assembly = '',$series='' ){
        $str="update uu_order_fx_details set concat_id='$r' where orderid='$r' limit 1";
        $GLOBALS['le']->query($str);

        foreach($c_infos as $row){

            $c_r=$this->s->Group_Order_Submit($row['member'],$row['lid'],
                $row['tid'],$row['begintime'],$row['endtime'],$row['tprice'],
                $row['tnum'],0,$row['ordername'],$row['ordertel'],
                $row['contacttel'],$row['salerid'],$row['sapply_did'],
                $row['paymode'],$row['ordermode'],$remoteorder,$assembly,
                $series,"1","$r",0,$row['sfz']);
            if($c_r>=100000){
                $str="update uu_order_fx_details set concat_id='$r' where orderid='$c_r'";
                $GLOBALS['le']->query($str);
				if($row['p_type']=='H'){
					if(!$this->ph->update_seat_order($c_r, $row['seats_ids'])){
						abc777\Syslog::write($c_r.'-'.$seats_ids_str, 'show_product_update_order.txt');
					}
				}
            }else{
				// 释放座位
				if($p_info['p_type'] == 'H'){
					if(!$this->ph->release_dync_seat($row['round_id'])){
						include_once '/var/www/html/new/d/class/abc/Syslog.class.php';
						abc777\Syslog::write($_SESSION['sid'], 'show_product_seat_release.txt');
					}
				}
                $this->errHandle("附属产品22下单出错".json_encode($row),$c_r);
            }
        }
    }

	
}
/**
 *分销下单类
 *分销商分销
 */
class DisOrder_H extends OrderSubmit_H{
    public function __construct($s,$p,$m){
        parent::__construct($s,$p,$m,0,0);
    }
}